// pages/team/teamDetail/teamDetail.js
const { favoriteAPI, lawyerAPI, commentAPI, orderAPI } = require('../../../utils/api.js');
const { mockAPI } = require('../../../utils/mockData');

Page({

  /**
   * 页面的初始数据
   */
  data: {
      serviceProject: [
          {
              'sName': "电话咨询",
              'sDesc': '电话咨询、快速响应',
              'sImg': '../../../static/images/dianhua.png',
              "sPrice": 100
          },
          {
              'sName': "图文咨询",
              'sDesc': '图文咨询、详细描述',
              'sImg': '../../../static/images/icon-jinridingdan.png',
              "sPrice": 200
          },
          {
              'sName': "在线咨询",
              'sDesc': '在线咨询、实时回复',
              'sImg': '../../../static/images/icon-tixianweichuli.png',
              "sPrice": 0
          },
      ],
      choice_index: 0, //选中服务项目的下标
      comments: [], // 用户评论
      commentsLoading: true,
      no_comment: "../../../static/images/no_comment.png",
      is_collect: 0, // 收藏状态，0 未收藏，2 已收藏
      lawyer_id: null, // 律师 ID，用于标识收藏的律师
      isLoggedIn: false, // 登录状态
      password: null, // 支付密码
      lawyerDetail: {} // 新增，存放律师详情
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      console.log(options.id);
      this.setData({
          lawyer_id: options.id
      });
      this.loadLawyerDetail(options.id); // 加载律师详情
      this.loadComments(options.id); // 加载评论
      this.checkLoginStatus();
      this.checkFavoriteStatus();
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (userInfo && token) {
      this.setData({
        isLoggedIn: true
      });
    } else {
      this.setData({
        isLoggedIn: false
      });
    }
  },

  /**
   * 检查收藏状态
   */
  async checkFavoriteStatus() {
    if (!this.data.isLoggedIn) {
      this.setData({
        is_collect: 0
      });
      return;
    }

    try {
      const res = await favoriteAPI.checkStatus(this.data.lawyer_id);
      this.setData({
        is_collect: res.data.isFavorited ? 2 : 0
      });
    } catch (error) {
      console.error('检查收藏状态失败:', error);
      // 如果检查失败，尝试从收藏列表获取状态
      try {
        const listRes = await favoriteAPI.list(1, 1000);
        const favoriteList = listRes.data.list || [];
        const isFavorited = favoriteList.some(item => item.lawyerId === this.data.lawyer_id);
        this.setData({
          is_collect: isFavorited ? 2 : 0
        });
      } catch (listError) {
        console.error('从收藏列表检查状态失败:', listError);
      }
    }
  },

  //获取支付密码
  getPwd(e) {
      var that = this;
      that.setData({
          password: e.detail.value
      })
  },
  //点击微信支付
  wxPay() {
      let that = this;
      if (that.data.password) {
          if (that.data.password == 123456) {
              // 获取当前选中的服务项
              const service = that.data.serviceProject[that.data.choice_index];
              // 创建订单
              mockAPI.createOrder({
                  lawyerId: that.data.lawyer_id,
                  serviceType: service.sName,
                  price: service.sPrice
              }).then(() => {
                  wx.showToast({
                      title: '支付成功！',
                      icon: 'success',
                      duration: 1500,
                      success: function () {
                          setTimeout(function () {
                              that.hideModal();
                              wx.navigateTo({
                                  url: '/pages/my/serviceOrder/serviceOrder?status=待付款'
                              });
                          }, 1000);
                      }
                  });
              });
          } else {
              wx.showToast({
                  title: '密码错误！',
                  icon: 'error',
                  duration: 2000
              });
          }
      } else {
          wx.showToast({
              title: '请输入支付密码！',
              icon: 'error',
              duration: 2000
          });
      }
  },
  //关闭模拟支付接口
  hideModal(e) {
      this.setData({
          modalName: null,
          password: null
      })
  },
  /**
   * 立即咨询
   */
  toSubscribe(e) {
      //打开支付窗口
      this.setData({
          modalName: e.currentTarget.dataset.target,
          password: null
      })

  },

  /**
   * 选择服务项目函数
   * @param {Object} e
   */
  choiceServe: function (e) {
      e = parseInt(e.currentTarget.dataset.index)
      this.setData({
          choice_index: e,
      });
  },

  /**
   * 收藏功能
   */
  collect() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const { is_collect, lawyer_id } = this.data;
    
    if (is_collect === 0) {
      // 添加收藏
      this.addFavorite(lawyer_id);
    } else {
      // 取消收藏
      this.cancelFavorite(lawyer_id);
    }
  },

  /**
   * 添加收藏
   */
  async addFavorite(lawyerId) {
    try {
      await favoriteAPI.add(lawyerId);
      this.setData({
        is_collect: 2
      });
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    } catch (error) {
      wx.showToast({
        title: error.message || '收藏失败',
        icon: 'none'
      });
    }
  },

  /**
   * 取消收藏
   */
  async cancelFavorite(lawyerId) {
    try {
      await favoriteAPI.cancel(lawyerId);
      this.setData({
        is_collect: 0
      });
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      });
    } catch (error) {
      wx.showToast({
        title: error.message || '取消收藏失败',
        icon: 'none'
      });
    }
  },

  /**
   * 返回首页
   */
  toHome() {
      wx.switchTab({
          url: '/pages/index/index'
      })
  },

  

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    console.log('触发分享，律师ID:', this.data.lawyer_id);
    return {
        title: '快来咨询专业律师',
        path: `/pages/team/teamDetail/teamDetail?id=${this.data.lawyer_id}`,
        imageUrl: '/static/images/law_bg.png' // 确保图片路径正确
    }
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLoginStatus();
    this.checkFavoriteStatus();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  async loadLawyerDetail(lawyerId) {
    try {
      const res = await lawyerAPI.detail(lawyerId);
      this.setData({ lawyerDetail: res.data || {} });
    } catch (e) {
      wx.showToast({ title: '律师信息加载失败', icon: 'none' });
    }
  },

  async loadComments(lawyerId) {
    this.setData({ commentsLoading: true });
    try {
      const res = await commentAPI.list(lawyerId, 'newest');
      this.setData({
        comments: res.data.list,
        commentsLoading: false,
      });
    } catch (error) {
      console.error('加载评论失败:', error);
      this.setData({ commentsLoading: false });
    }
  },

  async handleAddComment() {
    if (!this.data.isLoggedIn) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    try {
      // 查找当前用户与该律师之间已完成但未评价的订单
      const res = await mockAPI.getOrderList({ status: '已完成' }); // Use mock for simplicity
      const completdOrders = res.data.list || [];
      const orderToComment = completdOrders.find(o => o.lawyerId === this.data.lawyer_id && !o.comment);

      if (orderToComment) {
        wx.navigateTo({
          url: `/pages/my/orderComment/orderComment?id=${orderToComment.orderId}`,
        });
      } else {
        wx.showToast({
          title: '您与该律师暂无已完成或未评价的订单',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      wx.showToast({ title: '检查订单状态失败', icon: 'none' });
    }
  }
})